import store from '@/store'
import { logout } from '@/store/actions'
import { message } from 'antd'
import axios from 'axios'
import { history } from './history'
// 创建axios实例
const http = axios.create({
  baseURL: process.env.REACT_APP_URL,
  timeout: 5000
})
// 请求拦截器
http.interceptors.request.use(config=>{
  const state = store.getState()
  if(state.user.token){
    config.headers.Authorization = `Bearer ${state.user.token}`
  }
  return config
},e=>Promise.reject(e))


// 响应拦截器
http.interceptors.response.use(res => {
  return res?.data?.data || res
}, e => {
  if(e.response.status === 401){
    message.error('登录失效')
    store.dispatch(logout())
    // 防止跳转login的时候接口才处理401
    if ( history.location.pathname !== '/login') {
      history.push({
        pathname: '/login',
        state: { from: history.location.pathname }
      })
    }
  }
  return Promise.reject(e)
})

export { http }